package com.wx.jpa.config;

import com.wx.jpa.entity2.UserInfo2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @ClassName DataSourceTwoConfig
 * @Author wx
 * @Description 将数据-2源注入到实体管理器工厂
 * @Date 2018-12-26-22:44
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryTwo",//配置连接工厂 entityManagerFactory
        transactionManagerRef = "transactionManagerTwo", //配置 事物管理器  transactionManager
        basePackages = {"com.wx.jpa.respository2"}//设置dao（repo）所在位置
)
public class DataSourceTwoConfig {

    /**
     * 注入 mysql数据源2
     */
    @Autowired
    @Qualifier("dataSourceTwo")
    private DataSource dataSourceTow;

    @Bean(name = "entityManagerFactoryTwo")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryTwo(EntityManagerFactoryBuilder builder) {

        return builder
                //设置数据源
                .dataSource(dataSourceTow)
                //设置实体类所在位置.扫描所有带有 @Entity 注解的类
                .packages(UserInfo2.class)
                // Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
                // Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
                .persistenceUnit("dataSourceTowPersistenceUnit").build();

    }

    /**
     * @methodName: transactionManagerPrimary
     * @author: wx
     * @description: 配置事物管理器
     * @param builder
     * @date: 2018/12/26
     * @return: org.springframework.transaction.PlatformTransactionManager
     */
    @Bean(name = "transactionManagerTwo")
    public PlatformTransactionManager transactionManagerTwo(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryTwo(builder).getObject());
    }
}
